package com.example.a66666.yuejian.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.example.a66666.yuejian.Bean.LoginBean;
import com.example.a66666.yuejian.Listener.RetrofitListener;
import com.example.a66666.yuejian.Model.UserModel;
import com.example.a66666.yuejian.R;

public class LoginActivity extends AppCompatActivity  {

    private EditText username,userpass;
    private Button login,register;
    private Intent intent1,intent2;
    private UserModel usermodel;
    private RetrofitListener<LoginBean> listener;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        sp=getSharedPreferences("me",MODE_PRIVATE);
        editor=sp.edit();
        initView();
        initButton();
        initListener();
    }

    public void initView(){
        username=(EditText)findViewById(R.id.edit_username);
        userpass=(EditText)findViewById(R.id.edit_password);
        login=(Button)findViewById(R.id.btn_login);
        register=(Button)findViewById(R.id.btn_register);
    }

    public void initButton(){
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                usermodel=new UserModel();
                usermodel.userLogin(username.getText().toString(),userpass.getText().toString(),listener);
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent2=new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent2);
            }
        });
    }

    public void initListener(){
        listener=new RetrofitListener<LoginBean>() {
            @Override
            public void onSuccess(LoginBean loginBean) {
                if(0==loginBean.getFlag()){
                    Toast.makeText(LoginActivity.this,"用户名或密码错误",Toast.LENGTH_LONG).show();
                }
                else{
                    int uid=loginBean.getFlag();
                    editor.putInt("userid",uid);
                    editor.commit();
                    Toast.makeText(LoginActivity.this,String.valueOf(uid),Toast.LENGTH_LONG).show();
                    intent1=new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent1);
                }
            }
            @Override
            public void onFail(String msg) {
                Toast.makeText(LoginActivity.this,msg,Toast.LENGTH_LONG).show();
            }
        };
    }

}
